﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Db;
using Aandelendelen.Mail;
using Aandelendelen.Security;
using Aandelendelen.Obs;

namespace Aandelendelen.Controls
{
	public partial class PasswordForgottenControl : BaseUserControl
	{
		protected override void OnFirstHit(object sender, EventArgs e)
		{
			string uid = this.Request["uid"];

			if (string.IsNullOrEmpty(uid) == false)
			{
				this.tbGebruikersnaam.Text = uid;
			}
		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
			Page.Validate();

			if (Page.IsValid)
			{
				ResultSet resultSet = this.ValidateCustom();

				if (resultSet.Count != 1)
				{
					this.ErrorMessageControl1.Text = "Onbekende gebruikersnaam";
					this.ErrorMessageControl1.Show();
				}
				else
				{
					this.ErrorMessageControl1.Hide();

					this.ChangePassword(resultSet);

					Response.Redirect("/PasswordChanged.aspx", true);
				}
			}
		}


		public string Gebruikersnaam { get { return this.tbGebruikersnaam.Text.ToLower(); } }

		private ResultSet ValidateCustom()
		{
			Query query = new Query("s_getemail", "Gebruikersnaam", this.Gebruikersnaam, OleDbType.Char);

			return (ResultSet)query.Execute();
		}

		private void ChangePassword(ResultSet resultSet)
		{
			string newPwd = Hash.GetRandomPassword();
			string hashed = Hash.GetMD5Hash(newPwd);

			QueryArguments args = new QueryArguments();

			args.Add("Wachtwoord", hashed, OleDbType.Char);
			args.Add("Id", resultSet[0, "Id"], OleDbType.Integer);

			Query query = new Query("u_newpassword", args);

			query.Execute();

			Userinfo userInfo = new Userinfo(resultSet);
			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			mailArgs["{pwd}"] = newPwd;
			mailArgs["{aanhef}"] = userInfo.MailAanhef;

			EMail email = MailCache.GetMail("changepassword");
			email.Recipients = (string)resultSet[0, "Email"];

			email.QueueSingle();
		}
	}
}